package com.tarena.lbs.message.web.service.xxljobhandler;

import com.tarena.lbs.basic.api.UserGroupApi;
import com.tarena.lbs.common.message.constance.Const;
import com.tarena.lbs.message.web.service.MsgService;
import com.tarena.lbs.message.web.service.TimingMsgExecuteService;
import com.tarena.lbs.message.web.service.TimingMsgTemplateService;
import com.tarena.lbs.pojo.basic.vo.UserVO;
import com.tarena.lbs.pojo.message.dos.Msg;
import com.tarena.lbs.pojo.message.dos.TimingMsgTemplate;
import com.xxl.job.core.context.XxlJobHelper;
import java.util.List;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 定时任务到期后，执行该类
 *
 * */
@Service
@Slf4j
public class TimingMsgExecuteServiceImpl implements TimingMsgExecuteService {
    @Autowired
    MsgService msgService;

    @Autowired
    TimingMsgTemplateService timingMsgTemplateService;

    @Resource
    private UserGroupApi userGroupApi;

    /**
     * 定时任务到期后，推送消息
     * @param timingMsgTaskId 定时任务编号
     */
    @Override
    public void sendMessage(Integer timingMsgTaskId) {
        try {
            String logInfo="任务:"+timingMsgTaskId+"执行了";
            XxlJobHelper.log(logInfo);
            log.info("sendMessage logInfo={}",logInfo);
            //1,从消息表查询数据，
            List<Msg> msgList = msgService.selectByTimingMsgTaskId(timingMsgTaskId);
            for(Msg msg:msgList) {
                Integer userId = msg.getUserId();
                /*// 1.1websockt发通知
                WebSocketServer.sendLbsInfo(userId);*/

                //  1.2,更新消息表定时消息状态为可读
                msg.setStatus(1);
                TimingMsgTemplate timingMsgTemplate = timingMsgTemplateService.getMsgContent(msg.getTemplateId(),msg.getUserId());
                UserVO userVO = userGroupApi.getUser(msg.getUserId());
                String content = timingMsgTemplate.getContent().replace(Const.USER_NAME,userVO != null ? userVO.getUserName() : "");
                String msgTitle = timingMsgTemplate.getMsgTitle().replace(Const.USER_NAME,userVO != null ? userVO.getUserName() : "");
                msg.setMsgTitle(msgTitle);
                msg.setContent(content);
                msgService.updateMsgStatus(msg);

            }
        }catch (Exception e){

        }

    }
}
